package com.liezh.server;

import com.liezh.service.User;
import org.apache.thrift.TException;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TMessage;
import org.apache.thrift.protocol.TProtocol;

import java.util.Map;

/**
 * 装饰器模式
 * @author liezh
 * @date 2022-3-7
 */
public class THeaderProcessor implements TProcessor {

    private TProcessor realProcessor;

    public THeaderProcessor(TProcessor realProcessor) {
        this.realProcessor = realProcessor;
    }

    @Override
    public boolean process(TProtocol in, TProtocol out) throws TException {
        if (in instanceof THeaderServerProtocol) {
            // 解析thrift协议
            THeaderServerProtocol serverProtocol = (THeaderServerProtocol) in;
            serverProtocol.markTFramedTransport(in);
            TMessage tMessage = serverProtocol.readMessageBegin();
            // 读取0号字段，当作header
            serverProtocol.readFieldZero();
            Map<String, String> headInfo = serverProtocol.getHead();

            String username = headInfo.get("username");
            String id = headInfo.get("id");

            if (username != null && id != null) {
                System.out.println("username " + username);
                System.out.println("id " + id);
                UserSession.setSession(new User(Integer.valueOf(id), username, ""));
            }
            serverProtocol.resetTFramedTransport(in);
        }
        // 提交到业务处理器
        boolean result = realProcessor.process(in, out);
        if (in instanceof THeaderServerProtocol) {
            // TODO 请求后置逻辑
        }
        return result;
    }

}
